package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.utils.BaseContest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到用户id判断是否登录
        Long id = (Long) request.getSession().getAttribute("employee");
        if (id!=null) {
            //用户已登录 把登录人Id存入线程
            BaseContest.set(id);
            return true;
        }
        //拿到手机端用户id判断是否登录
        Long userid = (Long) request.getSession().getAttribute("user");
        if (userid!=null) {
            //用户已登录 把登录人Id存入线程
            BaseContest.set(userid);
            return true;
        }

        //用户没有登录,响应给前端数据
        R r = R.error("NOTLOGIN");
        //转json
        String s = JSON.toJSONString(r);
        response.getWriter().write(s);
        return false;
    }
}
